import {
  createRouter,
  createWebHistory,
  createWebHashHistory,
} from "vue-router";
import type { metaType } from "@/comTypes";
// import HomeView from '../views/HomeView.vue'
// type metaType = {
//   title: string //页面标题
//   color?: string //页面颜色
//   isNav?: true //是否在导航栏
//   index?: number //导航排序
// }

// 获取page.js文件信息作为meta
const modules = import.meta.glob("../views/**/page.ts", {
  eager: true,
  import: "default",
});
function getMatchPath(key: string) {
  const arr = key.split("/");
  arr.pop();
  return arr.join("/");
}
const modulesMap = new Map();
for (const [key, value] of Object.entries(modules)) {
  modulesMap.set(getMatchPath(key), value);
}

// 获取所有的vue文件对象
const routePaths = import.meta.glob("../views/**/*.vue");

function getPath(key: string) {
  if (key.includes("/index.vue")) {
    return (
      "/" +
      key.replace("../views", "").replace("/index.vue", "").split("/").at(-1)
    );
  }
  return "/" + key.split("/").at(-1)?.replace(".vue", "");
}

// 过滤掉非index.vue命名的文件
const indexRoutes = Object.entries(routePaths).filter(([key, value]) =>
  key.includes("/index.vue")
);
// 对过滤后的数据重组
const routes = indexRoutes.map(([key, value]) => {
  let path = getPath(key);
  if (path.includes("$")) {
    //@ts-ignore
    path = path.replaceAll("$", "/:");
  }

  let meta: metaType | {} = {};
  if (modulesMap.has(getMatchPath(key))) {
    meta = modulesMap.get(getMatchPath(key));
  }
  return {
    path,
    name: path?.replace("/", "") || "home",
    component: routePaths[key],
    meta,
    children: [] as any,
  };
});

function delEnd(str: string) {
  const arr = str.split(".");
  arr.pop();
  return arr.join(".");
}
routes.forEach((item: any, index) => {
  if (item.name.includes(".")) {
    item.path = item.path.replaceAll(".", "/");
    const idx = routes.findIndex((i) => i.name == delEnd(item.name));
    if (idx !== -1) {
      routes[idx].children.push(item);
    }
  }
});
const resRoutes = routes.filter((item) => !item.name.includes("."));

localStorage.setItem("routes", JSON.stringify(resRoutes));

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: resRoutes,
  // routes: [
  //   {
  //     path: "/about",
  //     name: "about",
  //     component: () => import("../views/about/index.vue"),
  //     children: [
  //       {
  //         path: "/about/child",
  //         name: "child",
  //         component: () => import("../views/about/child.vue"),
  //       },
  //     ],
  //   },
  // ],
});

export default router;
